﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LitS3;
using System.Net;
using System.IO;

namespace Natol.MSSyncFxProviders.AmazonS3
{
    public static class S3Helper
    {
        public static S3Service GetService(this S3BucketLoginData loginData, string defaultDelimiter)
        {
            var result = new S3Service()
            {
                AccessKeyID=loginData.AWSAccessKey,
                SecretAccessKey = loginData.AWSSecretKey,
                UseSsl=false,
                UseSubdomains=true,
                DefaultDelimiter=defaultDelimiter
            };

            //todo: add proxy stuff
            result.BeforeAuthorize += new EventHandler<S3RequestArgs>(result_BeforeAuthorize);
            
            return result;
        }

        static void result_BeforeAuthorize(object sender, S3RequestArgs e)
        {
            e.Request.Proxy = WebRequest.DefaultWebProxy;
            e.Request.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
            e.Request.ServicePoint.Expect100Continue = false;
            e.Request.ServicePoint.ConnectionLimit = Int32.MaxValue;
        }

        public static void CopyStream(Stream source, Stream dest, long length, Action<long> progressCallback)
        {
            var buffer = new byte[8192];

            if (progressCallback != null)
                progressCallback(0);

            long totalBytesRead = 0;
            while (totalBytesRead < length) // reuse this local var
            {
                int bytesRead = source.Read(buffer, 0, buffer.Length);

                if (bytesRead > 0)
                    dest.Write(buffer, 0, bytesRead);
                else
                    throw new Exception("Unexpected end of stream while copying.");

                totalBytesRead += bytesRead;

                if (progressCallback != null)
                    progressCallback(totalBytesRead);
            }
        }
    }
}
